const { bfmetaSDK } = require('../../../util/util')
const { signature, isAddress } = require('../../../util/signature')

// 发行模版 用于生成具体权益实体
const trTransferAsset = () => {
    return async (req, res, next) => {
      try {
        if(!req.body.recipientId || !req.body.amount || !req.body.publicKey){
            return res.status(400).send({
                success: false,
                message: "参数不能为空"
            })
        }
        if(typeof req.body.amount !== 'string' || typeof req.body.recipientId !== 'string' || typeof req.body.publicKey !== 'string'){
            return res.status(400).send({
                success: false,
                message: "参数类型必须为string"
            })
        }
        if(!( await isAddress(req.body.recipientId))){
            return res.status(400).send({
                success: false,
                message: "recipientId为非法地址"
            })
        
        }
        let data = {
          /**转移的权益数量，0-9 组成并且不包含小数点，必须大于 0 */
          amount: req.body.amount,
          recipientId: req.body.recipientId,
          /**转移的权益类型，大写字母组成，3-5 个字符 */
          assetType: "BFMTEST",
          publicKey: req.body.publicKey,
          fee: "2000",
          applyBlockHeight: 1
        }
        // 创建转账事件
        let result = await bfmetaSDK.api.transaction.createTransferAsset(data)
        if(!result.success){
            return res.status(400).send(result)
        }
        // 生成签名 验证转账事件
        const _signature = await signature(result.result.buffer, req.body.secretKey)
        data = {
          signature: _signature,
          buffer: result.result.buffer,
        }
        // 广播创建模版事件
        result = await bfmetaSDK.api.transaction.broadcastTransferAsset(data)
        res.status(200).send(result)
      } catch (error) {
        next(error)
      }
    }
  }
  
module.exports = {trTransferAsset}